package com.frontop.terminal.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpRequest;
import com.frontop.terminal.constant.InterfaceConst;
import com.frontop.terminal.entity.Message;
import com.frontop.terminal.entity.Program;
import com.frontop.terminal.entity.TerminalConfig;
import com.frontop.terminal.enums.HeaderEnum;
import com.frontop.terminal.model.vo.RestResult;
import com.frontop.terminal.service.ICommandSerivce;
import com.frontop.terminal.util.ReadDataUtil;
import com.frontop.terminal.util.SystemMonitoringUtil;
import com.frontop.terminal.util.WriteDataUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 移除互动程序业务
 * </p>
 *
 * @author Frontop
 * @since :2022-06-29
 **/
public class ProgramRemoveServiceImpl implements ICommandSerivce {
    /**
     * 执行业务
     *
     * @param message 消息对象
     * @return T
     */
    @SuppressWarnings("ConstantConditions")
    @Override
    public RestResult executeWork(Message message) {
        Map<String, Program> programMap = ReadDataUtil.getProgramListMap();
        if (ObjectUtil.isNull(programMap) && programMap.isEmpty()) {
            return RestResult.failed("程序列表为空");
        }


        if (programMap.containsKey(message.getCommand())) {

            programMap.remove(message.getCommand());

            List<Program> programList = new ArrayList<>(programMap.values());
            //save
            WriteDataUtil.write(programList, ReadDataUtil.PROGRAM_LIST_CODING);

            //通知中控移除成功
            String mac = SystemMonitoringUtil.getMacAddress();
            TerminalConfig terminalConfig = ReadDataUtil.getTerminalConfig();

            //忽略通知结果
            if (ObjectUtil.isNotNull(terminalConfig)) {
                String url = terminalConfig.getServerAddress() + InterfaceConst.REMOVE_RESOURCE_SUCCESS;
                HttpRequest.post(url)
                        .header(HeaderEnum.TERMINAL_TOKEN.getKey(), ReadDataUtil.getTerminalConfig().getAuthorizationCode())
                        .form("mac", mac)
                        .form("id", message.getCommand())
                        .executeAsync();
            }
        }

        return RestResult.success();
    }
}
